<?php
namespace app\index\controller;

use EasyWeChat\Factory;
use app\common\model\PieceShare;
use app\common\model\ProductPiece as ProductPieceModel;
use app\common\model\UserProductPiece;
use app\lib\exception\BaseException;
use think\Db;

class ProductPiece extends BaseController
{
    public function index(){
        if(!$piece_id = input('piece_id')){
            throw new BaseException(['msg'=>'没有碎片id']);
        }
        $piece = ProductPieceModel::getById($piece_id);
        $piece = $piece->toArray();
        $user_piece = UserProductPiece::
        where(['piece_id'=>$piece_id,'user_id'=>$this->user_info['id']])->field('user_id,piece_id,number')->find();
        $user_piece = $user_piece?$user_piece->toArray():[];
        $piece['number'] = !empty($user_piece['number'])?$user_piece['number']:0;
        $this->assign('piece',$piece);
        //微信分享
        $config = [
            'app_id' => config('ofcl.app_id'),
            'secret' => config('ofcl.app_secret'),

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        $this->assign('wx_config',$app->jssdk->buildConfig(array('onMenuShareTimeline', 'onMenuShareAppMessage'), false));
        //页面分享设置信息
        $share_info = model('page')->where('name="piece"')->find();
        if(!$share_info) throw new BaseException(['无页面分享信息！']);
        $share_info = $share_info->toArray();
        if($share_info['use_main_img']) {
            $share_info['img_url'] = $piece['img_url'];
        }
        $this->assign('share_info',$share_info);
        return successReturn($this->fetch());
    }
    public function share(){
        //检查id
        if(!$piece_id = input('piece_id')){
            throw new BaseException(['msg'=>'没有碎片id']);
        }
        Db::startTrans();
        try{
            //检查数量
            $user_piece = UserProductPiece::
            where(['piece_id'=>$piece_id,'user_id'=>$this->user_info['id']])
                ->field('user_id,piece_id,number,product_id')->find();
            if($user_piece->number <= 0){
                throw new BaseException(['msg'=>'数量不足！']);
            }
            //有可以分享
            $data = [
                'user_id'=>$this->user_info['id'],
                'piece_id'=>$piece_id,
                'nickname'=>$this->user_info['nickname'],
                'product_id'=>$user_piece->product_id
            ];
            //生成分享数据
            $share = PieceShare::create($data);
            $user_piece->setDec('number');
            Db::commit();
            return successReturn($share);
        }catch (\Exception $e){
            Db::rollback();
            throw $e;
        }
    }
    public function receive(){
        $data = input('param.');
        if(!$data['share_id']) throw new BaseException(['msg'=>'没有指定分享id！']);
        $share_data = PieceShare::getById($data['share_id']);
        if($share_data['user_id'] == $this->user_info['id']){
            throw new BaseException(['msg'=>'不能领取自己的分享！']);
        }
        if($share_data->is_received){
            throw new BaseException(['msg'=>'碎片已被领取！']);
        }
        Db::startTrans();
        try{
            UserProductPiece::incUserPiece($this->user_info['id'],$share_data['product_id'],$share_data['piece_id']);
            PieceShare::updateOne($data['share_id'],
                [
                    'is_received'=>1,
                    'receiver_nickname'=>$this->user_info['nickname'],
                    'receive_time'=>time()
                ]);
            Db::commit();
            $data = ProductPieceModel::getById($share_data['piece_id']);
            return successReturn($data,'恭喜您！领取到一块碎片！');
        }catch (\Exception $e){
            Db::rollback();
            throw $e;
        }
    }
    public function getNumberByUserId(){
        $piece_id = input('piece_id');
        $number = UserProductPiece::where([
            'user_id'=>$this->user_info['id'],
            'piece_id'=>$piece_id
        ])->value('number');
        return successReturn(['number'=>$number]);
    }
}
